package com.example.sppmode;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.util.LinkedList;
import java.util.Queue;

public class FunctionBlueToothCame {
    private static String TAG = "FunctionEJ";
    private static int FrameDataLen = 1036;
    private static int FrameHeaderLen = 10;
    private static int FrameEnderLen = 2;
//    1036 = 10 + 1024 + 2;


    private static Queue<byte[]> byteArrayQueue = new LinkedList<>();


    public static byte[] concat(byte[] firstA, int aLen, byte[] secondB, int bLen)
    {
        int resultLength = aLen + bLen;
        byte[] result = new byte[resultLength];
        System.arraycopy(firstA, 0, result, 0, aLen);
        System.arraycopy(secondB, 0, result, aLen, bLen);
        return result;

    }

    public static BlueToothCameData parasBlueToothCame(byte[] bytes, OnBluetoothAction onBluetoothAction) {
        BlueToothCameData blueToothData = new BlueToothCameData();
        if (bytes.length < FrameDataLen) //不满足一帧
        {
            blueToothData.dataLen = bytes.length;
            blueToothData.data = bytes;
            return blueToothData;
        } else //满足一帧
        {
            if (bytes[0] == -2 && bytes[1] == 4 && bytes[2] == 8 && bytes[3] == 41) //找到帧头, FrameHeaderLen
            {
                int subCount = ((bytes[6] & 0xFF) << 8) | (bytes[7] & 0xFF); //当前数据包号
                int subDataLen = ((bytes[8] & 0xFF) << 8) | (bytes[9] & 0xFF); //数据包有效数据长度

                Log.d("EJV3_CAMERA", "run dataSub count: " + subCount);
                Log.d("EJV3_CAMERA", "run data len: " + bytes.length);
                //一帧有效长度为：1024，第19帧有效长度为：384（112*112*1.5 - 1024*18 = 384）
                //一帧有效长度为：1024，第19帧有效长度为：384（112*112 - 1024*12 = 1024*12）

                if(subCount != 13)
                {
                    int availDataLen = FrameDataLen - FrameHeaderLen - FrameEnderLen; //1024
                    byte[] frameData = new byte[availDataLen];
                    System.arraycopy(bytes, FrameHeaderLen, frameData, 0, availDataLen);
                    byteArrayQueue.offer(frameData);
                }else
                {
                    int availDataLen = 256;
                    byte[] frameData = new byte[availDataLen];
                    System.arraycopy(bytes, FrameHeaderLen, frameData, 0, availDataLen);
                    byteArrayQueue.offer(frameData);

                    byte[] mergedYUVImage  = mergeYUVImages(byteArrayQueue);
                    Bitmap bitmap =  convertYToBitmap(mergedYUVImage, 112, 112);

                    onBluetoothAction.onReceiveCame(bitmap, 112, 112);
                }

            }
            return blueToothData;

        }
    }

    private static int calculateTotalLength(Queue<byte[]> byteArrayQueue) {
        int totalLength = 0;

        // 遍历队列中的每个 byte[] 数组，并累加它们的长度
        for (byte[] array : byteArrayQueue) {
            totalLength += array.length;
        }

        return totalLength;
    }

    // 合并 YUV 数据的函数
    private static byte[] mergeYUVImages(Queue<byte[]> byteArrayQueue) {
        // 计算合并后数组的总长度
        int totalLength = calculateTotalLength(byteArrayQueue);

        // 创建一个新的字节数组用于存储合并后的数据
        byte[] mergedArray = new byte[totalLength];

        int currentPosition = 0;

        // 逐一从队列中取出数据并拼接
        while (!byteArrayQueue.isEmpty()) {
            byte[] currentArray = byteArrayQueue.poll(); // 从队列中取出 YUV 数据
            System.arraycopy(currentArray, 0, mergedArray, currentPosition, currentArray.length); // 拼接
            currentPosition += currentArray.length; // 更新当前位置
        }
        return mergedArray;
    }

    private static Bitmap convertYUVToBitmap(byte[] yuvData, int width, int height) {
        // YUV数据假设为 NV21 格式
        // 将 YUV 数据封装到 YuvImage 中
        YuvImage yuvImage = new YuvImage(yuvData, ImageFormat.NV21, width, height, null);

        // 将 YuvImage 转换为 Bitmap，输出的 ByteArrayOutputStream 用于接口压缩
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        yuvImage.compressToJpeg(new Rect(0, 0, width, height), 100, baos);

        // 将压缩后的 JPEG 数据转换为 Bitmap
        byte[] jpegData = baos.toByteArray();
        return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length);
    }

    private static Bitmap convertYToBitmap(byte[] yuvData, int width, int height) {
        // 创建一个Bitmap对象
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        // 确保在数据长度足够并且匹配 bitmap 尺寸
        if (yuvData.length < width * height) {
            return bitmap;
        }

        // 遍历Y值数组并设置像素
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                // 取得Y值
                int yIndex = y * width + x;
                int yValue = yuvData[yIndex] & 0xFF; // 转换为0-255范围

                // 将Y值转换为ARGB
                int pixelColor = Color.argb(255, yValue, yValue, yValue);

                // 将像素设置到Bitmap
                bitmap.setPixel(x, y, pixelColor);
            }
        }

        return bitmap;
    }

    public static class BlueToothCameData {
        public int dataLen = 0;
        public byte[] data = new byte[0];
    }


}
